'use strict';

exports.main = async (event, context) => {
  const { orderId, rating } = event.data;
  
  if (!orderId) {
    return {
      code: 400,
      message: '订单ID不能为空',
      data: null
    };
  }
  
  if (!rating || typeof rating !== 'object') {
    return {
      code: 400,
      message: '评价数据格式错误',
      data: null
    };
  }
  
  if (!rating.overall_score) {
    return {
      code: 400,
      message: '总体评分不能为空',
      data: null
    };
  }

  try {
    const db = uniCloud.database();
    
    // 首先检查订单是否存在且状态为已完成
    const orderRes = await db.collection('food-order').doc(orderId).get();
    
    if (!orderRes.data || orderRes.data.length === 0) {
      return {
        code: 404,
        message: '订单不存在',
        data: null
      };
    }
    
    const order = orderRes.data[0] || orderRes.data;
    
    // 检查订单状态，只允许对已完成订单进行评价
    if (order.status !== 3) {
      return {
        code: 403,
        message: '只能对已完成的订单进行评价',
        data: null
      };
    }
    
    // 构建更新数据
    const updateData = {
      rating: {
        overall_score: rating.overall_score,
        overall_comment: rating.overall_comment || null,
        dishes: Array.isArray(rating.dishes) ? rating.dishes : [],
        rated: true,
        rated_date: new Date()
      }
    };

    // 更新订单
    const updateRes = await db
      .collection('food-order')
      .doc(orderId)
      .update(updateData);

    // 检查是否更新成功
    const updated = updateRes.updated || 0;

    if (updated > 0) {
      return {
        code: 200,
        message: '评价提交成功',
        data: {
          orderId: orderId
        }
      };
    } else {
      return {
        code: 500,
        message: '评价提交失败',
        data: null
      };
    }
  } catch (error) {
    console.error('提交评价出错:', error);
    return {
      code: 500,
      message: error.message || '提交评价失败',
      data: null
    };
  }
};

